package com.webside.distinguish.controller;

 
 
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.webside.base.basecontroller.BaseController;
import com.webside.distinguish.model.Distinguish;
import com.webside.distinguish.model.SeriesDistinguish;
import com.webside.distinguish.model.SeriesDistinguishKey;
import com.webside.distinguish.service.DistinguishService;
import com.webside.distinguish.service.SeriesDistinguishService;
import com.webside.dtgrid.model.Pager;
import com.webside.dtgrid.util.ExportUtils;
import com.webside.exception.AjaxException;
import com.webside.exception.ServiceException;
import com.webside.exception.SystemException;
import com.webside.series.model.Bdictionary;
import com.webside.series.service.BdictionaryService;
import com.webside.series.service.BvideoService;
import com.webside.series.service.SeriesService;
import com.webside.util.Common;
import com.webside.util.CommonUtils;
import com.webside.util.PageUtil;


@Controller
@Scope("prototype")
 
@RequestMapping("/distinguish/")
public class DistinguishController extends BaseController {
 
	@Autowired
	private SeriesService seriesService;
	@Autowired
	private BdictionaryService bdictionaryService;
	@Autowired
	private BvideoService bvideoService;
	@Autowired
	private DistinguishService distinguishService;
	@Autowired
	private SeriesDistinguishService seriesDistinguishService;
	
	
	@RequestMapping("listUI.html")
	public String listUI(Model model,Long seriesId, HttpServletRequest request) {
		try
		{
			PageUtil page = new PageUtil();
			if(request.getParameterMap().containsKey("page")){
				page.setPageNum(Integer.valueOf(request.getParameter("page")));
				page.setPageSize(Integer.valueOf(request.getParameter("rows")));
				page.setOrderByColumn(request.getParameter("sidx"));
				page.setOrderByType(request.getParameter("sord"));
			}
			model.addAttribute("page", page);
			return Common.BACKGROUND_PATH + "/distinguish/list";
		}catch(Exception e)
		{
			throw new SystemException(e);
		}
	}
	
	
	/**
	 * ajax分页动态加载模式
	 * @param dtGridPager Pager对象
	 * @throws Exception
	 */
	@RequestMapping(value = "/list.html", method = RequestMethod.POST)
	@ResponseBody
	public Object list(Model model, Long distinguishId, String gridPager, HttpServletResponse response) throws Exception {
		
		Map<String,Object> parameters = null;
		// 映射Pager对象
		Pager pager = JSON.parseObject(gridPager, Pager.class);
		// 判断是否包含自定义参数
		parameters = pager.getParameters();
		if (parameters.size() < 0) {
			parameters.put("name", null);
		}//3、判断是否是导出操作
		if(pager.getIsExport())
		{
			if(pager.getExportAllData())
			{
				//3.1、导出全部数据
				List<Distinguish> list = distinguishService.queryListByPage(parameters);
				ExportUtils.exportAll(response, pager, list);
				return null;
			}else
			{
				//3.2、导出当前页数据
				ExportUtils.export(response, pager);
				return null;
			}
		}else{
			// 设置分页，page里面包含了分页信息
			Page<Object> page = PageHelper.startPage(pager.getNowPage(),pager.getPageSize());
		
			List<Distinguish> list = distinguishService.queryListByPage(parameters);
			parameters.clear();
			parameters.put("isSuccess", Boolean.TRUE);
			parameters.put("nowPage", pager.getNowPage());
			parameters.put("pageSize", pager.getPageSize());
			parameters.put("pageCount", page.getPages());
			parameters.put("recordCount", page.getTotal());
			parameters.put("startRecord", page.getStartRow());
			//列表展示数据
			parameters.put("exhibitDatas", list);
			return parameters;
		}
		
	}
	
	
	
	@RequestMapping("addUI.html")
	public String addUI(Model model) {
		
		
		return Common.BACKGROUND_PATH + "/distinguish/form";
	}
	//添加
	@RequestMapping("add.html")
	@ResponseBody
	public Object add(Distinguish distinguish) throws AjaxException
	{
		Map<String, Object> map = new HashMap<String, Object>();
		int isNameExist = distinguishService.isNameExist(distinguish.getName());
		
		try
		{
			if(isNameExist > 0){
				map.put("success", Boolean.FALSE);
				map.put("data", null);
				map.put("message", "添加失败,有相同分组名称");
			}else{
				distinguish.setCreateTime(new Date());
				distinguish.setDeleteState(true);
				int count=distinguishService.insert(distinguish);
				 
				if(count >0 )
				{ 
					map.put("success", Boolean.TRUE);
					map.put("data", null);
					map.put("message", "添加成功");
				}else
				{
					map.put("success", Boolean.FALSE);
					map.put("data", null);
					map.put("message", "添加失败");
				}
			}
		}catch(ServiceException e)
		{
			throw new AjaxException(e);
		}
		return map;
	}
	

	
	//修改显示
		@RequestMapping("editUI.html")
		public String editUI(Model model, HttpServletRequest request, Long id) {
			try
			{
				Distinguish distinguish = distinguishService.findById(id);
				PageUtil page = new PageUtil();
				page.setPageNum(Integer.valueOf(request.getParameter("page")));
				page.setPageSize(Integer.valueOf(request.getParameter("rows")));
				page.setOrderByColumn(request.getParameter("sidx"));
				page.setOrderByType(request.getParameter("sord"));
			
				model.addAttribute("page", page);
				model.addAttribute("distinguish", distinguish);

				return Common.BACKGROUND_PATH + "/distinguish/form";
			}catch(Exception e)
			{
				throw new SystemException(e);
			}
		}
		//修改
		@RequestMapping("edit.html")
		@ResponseBody
		public Object update(Distinguish distinguish)
		{
			Map<String, Object> map = new HashMap<String, Object>();
			try
			 {  	 
					
				int result = distinguishService.update(distinguish);
				System.out.println(result);
				if(result >0)
				{
					map.put("success", Boolean.TRUE);
					map.put("data", null);
					map.put("message", "编辑成功");
					
				}else
				{
					map.put("success", Boolean.FALSE);
					map.put("data", null);
					map.put("message", "编辑失败");
				}
			}catch(Exception e)
			{
				throw new AjaxException(e);
			}
			return map;
		}
		
		//删除
		@RequestMapping("deleteBatch.html")
		@ResponseBody
		public Object deleteBatch(String ids) {
			Map<String, Object> result = new HashMap<String, Object>();
			try
			{
				String[] seriesIds = ids.split(",");
				List<Long> list = new ArrayList<Long>();
				for (String string : seriesIds) {
					list.add(Long.valueOf(string));
				}
				int cnt = distinguishService.deleteBatchById(list);
				System.out.println(cnt);
				if(cnt == list.size())
				{
					result.put("success", true);
					result.put("data", null);
					result.put("message", "删除成功");
				}else
				{
					result.put("success", false);
					result.put("data", null);
					result.put("message", "删除失败");
				}
			}catch(Exception e)
			{
				throw new AjaxException(e);
			}
			return result;
		}
		
		/**
		 * 资源弹出
		 * @param model
		 * @param code
		 * @return
		 */
		@RequestMapping("SeriesResources.html")
		public String resources(Model model,Long distinguishId) {
			System.out.println(distinguishId+"=================");
			/*Map parameters = new HashMap<>();
			parameters.put("distinguishId", distinguishId);*/
			PageUtil sdListPageUtil =new PageUtil();
			sdListPageUtil.setPageNum(0);
			sdListPageUtil.setPageSize(15);
			List<SeriesDistinguish> sdList = null;
			sdList =seriesDistinguishService.selectListByDistinguishId(distinguishId);
			model.addAttribute("distinguishId",distinguishId);
			model.addAttribute("seriesDistinguishList",sdList);
			PageUtil pageUtil =new PageUtil();
			pageUtil.setPageNum(0);
			pageUtil.setPageSize(15);
			List<HashMap<String,Object>> list=seriesService.querySeries(pageUtil, "","");
			/*if(list.size()>0){
				SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				List<String> datelist=new ArrayList<String>();
				for(int i=0;i<list.size();i++){
					String edate=format.format(list.get(i).get("end_date"));
					datelist.add(edate);
				}
				model.addAttribute("datelist",datelist);
			}*/
			model.addAttribute("seriesResourceList",list);
			int SeriesCount = seriesService.countAll();
			model.addAttribute("seriesCount",SeriesCount);
			int count = SeriesCount;
			int totalPageCount;
			if(count>15 ){
				totalPageCount=count/15;
				 if(count%15==0){
					 model.addAttribute("totalPageCount", totalPageCount);
					  
					}else{
						model.addAttribute("totalPageCount", totalPageCount+1);}
			}else{
				totalPageCount=0;
				model.addAttribute("totalPageCount", totalPageCount);
			}
			
			System.out.println("剧集数："+count);
			return Common.BACKGROUND_PATH + "/distinguish/seriesResources";
		}

		/**
		 * 分组收录视频
		 */
		@RequestMapping(value="/addIn.html", method={RequestMethod.GET,RequestMethod.POST})
		@ResponseBody
		public String addSubjectSeries(Model model, Long distinguishId,int seriesId){
			SeriesDistinguishKey key = new SeriesDistinguishKey();
			key.setDistinguishId(distinguishId);
			key.setSeriesId(seriesId+"");
			
			SeriesDistinguish sd = seriesDistinguishService.SelectByPrimaryKey(key);
			if(sd == null){
				seriesDistinguishService.add(key);
			}
			//List<SeriesDistinguish> list = seriesDistinguishService.selectListByDistinguishId(distinguishId);
			return "success";
		}

		/**
		 * 分组批量收录视频
		 */
		@RequestMapping(value="/addListIn.html", method={RequestMethod.GET,RequestMethod.POST})
		@ResponseBody
		public String addManySeries(Model model, Long distinguishId,String seriesId){
			List<SeriesDistinguishKey> keyList = new ArrayList<SeriesDistinguishKey>();
			JSONArray jsonArray = JSONArray.parseArray(seriesId);
			Object[] obj = CommonUtils.toArrays(jsonArray);
			for (int i = 0; i < obj.length; i++) {
				SeriesDistinguishKey key = new SeriesDistinguishKey();
				String id = (String)obj[i];
				key.setDistinguishId(distinguishId);
				key.setSeriesId(id);
				keyList.add(key);
			}
			seriesDistinguishService.addList(keyList);
			return "success";
		}

		
		/**
		 * 分组删除视频
		 */
		@RequestMapping(value="/clean.html", method={RequestMethod.POST})
		@ResponseBody
		public int cleanDistinguishSeries(Model model, Long distinguishId, int seriesId){
			SeriesDistinguishKey key = new SeriesDistinguishKey();
			key.setDistinguishId(distinguishId);
			key.setSeriesId(seriesId+"");
			
			SeriesDistinguish sd = seriesDistinguishService.SelectByPrimaryKey(key);
			if(sd == null){
				return 0;
			}else{
				//List<SeriesDistinguish> list = seriesDistinguishService.selectListByDistinguishId(distinguishId);
				return seriesDistinguishService.deleteById(key);
			}
		}
		
		/**
		 * 分组批量收录视频
		 */
		@RequestMapping(value="/deleteListIn.html", method={RequestMethod.GET,RequestMethod.POST})
		@ResponseBody
		public String deleteManySeries(Model model, Long distinguishId,String seriesId){
			List<String> keyList = new ArrayList<String>();
			JSONArray jsonArray = JSONArray.parseArray(seriesId);
			Object[] obj = CommonUtils.toArrays(jsonArray);
			for (int i = 0; i < obj.length; i++) {
				String id = (String)obj[i];
				keyList.add(id);
			}
			Integer delete = seriesDistinguishService.deleteByIds(distinguishId, keyList);
			return delete.toString();
		}
		
		@RequestMapping(value="/bindSeries",method={RequestMethod.GET} )
		public String distinguishSeries(Model model,Long distinguishId){
			//剧集类型（CHANNEL）
			List<Bdictionary> dictList = bdictionaryService.selectChannels(null);
			model.addAttribute("dictList", dictList);
			model.addAttribute("distinguishId", distinguishId);
			System.out.println(distinguishId);
			return Common.BACKGROUND_PATH + "/distinguish/distinguishSeries";
		}
		
		@RequestMapping(value="/getOutSeries",method={RequestMethod.GET})
		@ResponseBody
		public  Map<String, Object> getNotDistinguishSeries(int pageNo, int pageSize, String channelCode, String keyWord, Long distinguishId){
			
			Map<String, Object> map = seriesService.selectSeriesByChannelAndNameNotInDistinguish(channelCode, keyWord, pageNo, pageSize,distinguishId);
			
			return map;
		}
		
		@RequestMapping(value="/getInSeries",method={RequestMethod.GET})
		@ResponseBody
		public  Map<String, Object> getDistinguishSeries(int pageNo, int pageSize, String channelCode, String keyWord, Long distinguishId){
			System.out.println("pageNo--"+pageNo+"--pageSize--"+pageSize+"--channelCode--"+channelCode+"--keyWord--"+keyWord+"--distinguishId--"+distinguishId);
			Map<String, Object> map = seriesService.selectSeriesByChannelAndNameInDistinguish(channelCode, keyWord, pageNo, pageSize,distinguishId);
			return map;	
		}
		
		
 	
}
